﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Windows.Interactivity;
using JHMVVMFramework;


namespace JHMVVMFramework.Common.Command
{
    [ContentProperty("Value")]
    public class CommandArg : DependencyObject, IEquatable<CommandArg>
    {
        bool m_isSetKey =false;

        private const string KEY_CAN_NOT_NULL = "Key can not been null";
        private const string KEY_HAS_BEEN_SET = "Key has been set";

        #region DependencyProperty
        private static readonly DependencyProperty KeyProperty = DependencyProperty.Register("Key", typeof(string), typeof(CommandArg), new PropertyMetadata(new Random().Next().ToString(), KeyPropertyChanged));
        private static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Object), typeof(CommandArg), new PropertyMetadata(null));

        private static void KeyPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(Convert.ToString(e.NewValue)) && string.IsNullOrEmpty(Convert.ToString(e.NewValue)))
                throw new ArgumentException(KEY_CAN_NOT_NULL);
        }

        public string Key
        {
            get { return Convert.ToString(GetValue(KeyProperty)); }
            set
            {
                if (string.IsNullOrWhiteSpace(value as string))
                {
                    throw new ArgumentException(KEY_CAN_NOT_NULL);
                }
                else
                {
                    if (m_isSetKey == false)
                    {
                        SetValue(KeyProperty, value);
                        m_isSetKey = true;
                    }
                    else
                    {
                        throw new InvalidOperationException(KEY_HAS_BEEN_SET);
                    }
                }
            }
        }

        public Object Value
        {
            get { return GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
        #endregion

        #region IEquatable接口实现

        public bool Equals(CommandArg other)
        {
            if (other == null) return false;
            return string.Equals(Key, other.Key, StringComparison.InvariantCultureIgnoreCase) && Value == other.Value;
        }

        #endregion

        public override string ToString()
        {
            return string.Format("({0},{1})", this.Key, this.Value);
        }
    }
}
